<template>
  <div>
    <van-nav-bar
      title="修改地址"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-address-edit
      :area-list="areaList"
      :address-info="addressInfo"
      show-postal
      show-delete
      show-set-default
      show-search-result
      :search-result="searchResult"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import { AddressEdit, NavBar, Toast } from 'vant'
import areaList from '@/components/area'

export default {
  components: {
    [AddressEdit.name]: AddressEdit,
    [NavBar.name]: NavBar
  },
  data () {
    return {
      areaList,
      addressInfo: { id: '', name: '', tel: '', county: '', areaCode: '', addressDetail: '' },
      searchResult: []
    }
  },
  async created () {
    const id = this.$route.params.id
    await this.getAddress(id)
  },
  methods: {
    onClickLeft () {
      this.$router.go(-1)
    },
    async getAddress (id) {
      const { data } = await this.$api.account.addressDetail(id)
      if (data.code !== 200) {
        Toast(data.desc)
      } else {
        const addr = data.data
        this.addressInfo = {
          id: addr.id,
          name: addr.receiver_name,
          tel: addr.receiver_phone,
          areaCode: addr.area.code,
          addressDetail: addr.detail_address,
          isDefault: addr.default_address,
          postalCode: addr.zip_code
        }
      }
    },
    async onSave (item) {
      console.log(item)
      const params = {
        id: item.id,
        receiver_name: item.name,
        receiver_phone: item.tel,
        area: item.areaCode,
        detail_address: item.addressDetail,
        zip_code: item.postalCode,
        default_address: item.isDefault
      }
      const { data } = await this.$api.account.addressPatch(item.id, params)
      if (data.code !== 200) {
        Toast(data.desc)
      } else {
        Toast('修改成功！')
        this.$router.go(-1)
      }
    },
    async onDelete (item) {
      const { data } = await this.$api.account.addressDelete(item.id)
      if (data.code !== 200) {
        Toast('删除出错，请稍后再试!')
      } else {
        Toast('删除成功!')
        this.$router.go(-1)
      }
    },

    onChangeDetail (val) {
      console.log(val)
      Toast('dianji')
      this.searchResult = val ? this.$t('searchResult') : []
    }
  }
}
</script>

<style>
</style>
